<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>原生JS实现购物车结算功能代码</title>
    <link rel="stylesheet" href="../css/style.css" />
    <style>
        .goods span {
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
            text-overflow: ellipsis;

        }
    </style>
</head>

<body>
    <div class="catbox">
        <table id="cartTable">
            <thead>
                <tr>
                    <th><label>
                            <input class="check-all check" type="checkbox" />&nbsp;&nbsp;全选</label></th>
                    <th>商品</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <!-- <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/1.jpg" alt="" /><span>Casio/卡西欧 EX-TR350</span></td>
                    <td class="price">5999.88</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">5999.88</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/2.jpg" alt="" /><span>Canon/佳能 PowerShot SX50 HS</span></td>
                    <td class="price">3888.50</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">3888.50</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/3.jpg" alt="" /><span>Sony/索尼 DSC-WX300</span></td>
                    <td class="price">1428.50</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">1428.50</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/4.jpg" alt="" /><span>Fujifilm/富士 instax mini 25</span></td>
                    <td class="price">640.60</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">640.60</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr> -->
            </tbody>
        </table>
        <div class="foot" id="foot">

            <a class="fl" id="deleteAll" href="javascript:;">删除</a>
            <div class="fr closing" onclick="getTotal();">结 算</div>
            <input type="hidden" id="cartTotalPrice" />
            <div class="fr total">合计：￥<span id="priceTotal">0.00</span></div>
            <div class="fr selected" id="selected">已选商品<span id="selectedTotal">0</span>件<span
                    class="arrow up">︽</span><span class="arrow down">︾</span></div>
            <div class="selected-view">
                <div id="selectedViewList" class="clearfix">
                    <div><img src="../images/1.jpg"><span>取消选择</span></div>
                </div>
                <span class="arrow">◆<span>◆</span></span>
            </div>
        </div>
    </div>
</body>
<script>

    var checkAll = document.getElementsByClassName("check-all")[0];
    var checkOneList = document.getElementsByClassName("check-one");
    var selectedTotal = document.getElementById("selectedTotal");
    var priceTotal = document.getElementById("priceTotal");

    var catbox = document.getElementsByClassName("catbox")[0];
    var tbody = document.querySelector("#cartTable tbody");



    var xhr = new XMLHttpRequest();

    xhr.open("get", "../data/shoppingCar.json", true);

    xhr.send();

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var result = xhr.responseText;

            result = JSON.parse(result);
            console.log(result);

            var { list } = result;

            var html = "";
            list.forEach(({ goodsName, goodsImg, goodsPrice, buyNum }) => {
                html += `<tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods">
                        <img src="${goodsImg}" alt="" />
                        <span>${goodsName}</span>
                    </td>
                    <td class="price">${goodsPrice}</td>
                    <td class="count"><span class="reduce">${buyNum > 1 ? "-" : ""}</span>
                        <input class="count-input" type="text" value="${buyNum}" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">${(goodsPrice * buyNum).toFixed(2)}</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>`
            })
            tbody.innerHTML = html; // 动态生成 -> 将拼接的html结构放到页面中 -> 渲染成对应的元素


        }
    }



    // ajax动态生成的问题 -> ajax请求是异步操作 ->   JS会先执行所有的同步任务 -> 等所有同步代码执行完毕,且 xhr.readyState状态改变以后 -> 才会触发对应的事件 -> 将xhr.onreadystatechange对应的函数拿到主线程中执行!!

    // 在我们获取元素(加 减 删除 反选),绑定事件时,它们还未生成  =>  获取的元素集合都是[] => 无法给[]集合中的元素绑定事件
    // console.log("反选", checkOneList);
    // console.log("加", addList);
    // console.log("减", reduceList);


    // 解决方法:
    // 1. 老赖行为  => 等元素动态生成之后 再获取元素绑定事件
    // 2. 利用事件委托 -> 将子元素的事件委托给父元素 由父元素代为执行 (可以给未来生成的元素绑定事件)


    catbox.onclick = function (e) {
        var e = e || window.event;
        var target = e.target;  // 获取事件源(触发事件的元素)

        if (target.classList.contains("check-all")) {
            console.log("点击了全选");
            // 所有的单选跟随全选的状态
            checkAllHandler.call(target);
            getTotal();

        } else if (target.classList.contains("check-one")) {
            console.log("点击了单选");
            isAllChecked();
            getTotal();

        } else if (target.className == "add") {
            console.log("点击了加号");
            addHandler.call(target);
            getTotal();

        } else if (target.className == "reduce") {
            console.log("点击了减号");
            reduceHandler.call(target);
            getTotal();

        } else if (target.className == "delete") {
            console.log("点击了单删");
            deleteOneHandler.call(target);
            isAllChecked(); // 删除之后 判断剩余的商品是否全部被选中
            getTotal();

        } else if (target.id == "deleteAll") {
            console.log("点击了全删");
            deleteAllHandler.call(target);
            isAllChecked(); //  删除之后 判断剩余的商品是否全部被选中
            getTotal();
        }



    }


    function checkAllHandler() {
        var status = this.checked;  //获取全选的状态
        console.log(status);

        // 所有的单选跟随全选的状态 -> 每一个单选跟全选的状态保持一直
        for (var i = 0; i < checkOneList.length; i++) {
            var checkOne = checkOneList[i];
            checkOne.checked = status;
        }
    }

    function isAllChecked() {
        var flag = Array.from(checkOneList).every(item => item.checked);
        checkAll.checked = checkOneList.length == 0 ? false : flag;
    }


    function addHandler() {
        console.log(this);

        // a.  输入框  数量 加一
        var countInput = this.previousElementSibling; // 先获取输入框
        var num = countInput.value; // 取输入框的值 赋值给变量num
        num++;
        countInput.value = num; // 将更新后的结果 赋值给输入框
        // 可以简写
        // countInput.value ++;

        // b. 小计更新 = 单价 * 数量
        // 单价: 从页面获取  (加号的父元素的前一个)
        // 数量: num

        var parentTd = this.parentElement; // 父元素
        var priceTd = parentTd.previousElementSibling; //父元素的前一个
        var subtotalTd = parentTd.nextElementSibling; // 父元素的后一个

        var price = priceTd.textContent * 1;
        var subtotal = price * num;
        subtotalTd.textContent = subtotal.toFixed(2);

        // c.  减号按钮的 “-”  出现
        var reduce = countInput.previousElementSibling;
        reduce.textContent = "-";

    }


    function reduceHandler() {

        // a. 输入框  数量 减一   
        var countInput = this.nextElementSibling; // 先获取输入框
        var num = countInput.value; // 取输入框的值 赋值给变量num

        // c. 减之前  判断  如果数量为1  不能减 (不执行后续代码)  
        if (num <= 1) { //最小值判断
            alert("亲,不能再少了");
            return false
        };

        num--;  //自减

        // d. 减之后  判断  如果数量为1  减号按钮的 “-” 消失(2切1)
        if (num <= 1) { // (2切1时 减号按钮文本消失)
            this.textContent = "";
        }

        countInput.value = num; // 将更新后的结果 赋值给输入框

        // b. 小计更新 = 单价 * 数量 

        var parentTd = this.parentElement; // 父元素
        var priceTd = parentTd.previousElementSibling; //父元素的前一个
        var subtotalTd = parentTd.nextElementSibling; // 父元素的后一个

        var price = priceTd.textContent * 1;
        var subtotal = price * num;
        subtotalTd.textContent = subtotal.toFixed(2);
    }


    function deleteOneHandler() {
        console.log(this);

        if (confirm("是否删除该商品?")) { //删除之前 添加一个确认操作
            var tr = this.parentElement.parentElement;
            tr.remove();
        }

    }


    function deleteAllHandler() {
        // debugger;
        for (let i = 0; i < checkOneList.length; i++) {
            let checkOne = checkOneList[i]; //找到每一个单选框
            if (checkOne.checked) {
                var tr = checkOne.parentElement.parentElement;
                tr.remove();
                i--;
            }
        }
    }


    function getTotal() {
        // 每次调用此方法 => 都会重新找到所有选中状态的checkOne -> 根据它找到对应商品的数量和小计 -> 累加输出
        var sum = 0;
        var allPrice = 0;
        for (var j = 0; j < checkOneList.length; j++) {
            var item = checkOneList[j];//每一个checkOne
            if (item.checked) {  // 选中状态的checkOne
                // 通过选中状态的checkOne -> 查找对应的数量和小计
                var tr = item.parentElement.parentElement; //先找tr
                var countInp = tr.getElementsByClassName("count-input")[0]; //再找countInput
                var subtotalTd = tr.getElementsByClassName("subtotal")[0]; // 找subtotalTd

                var num = countInp.value * 1;
                var subtotal = subtotalTd.textContent * 1;

                sum += num;
                allPrice += subtotal;

            }
        }

        selectedTotal.textContent = sum;
        priceTotal.textContent = allPrice.toFixed(2);
    }





</script>

</html>